<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>todolist</title>
</head>
<body>

<div id="example"></div>


<script type="text/javascript" src="../js/react.development.js"></script>
<script type="text/javascript" src="../js/react-dom.development.js"></script>
<script type="text/javascript" src="../js/prop-types.js"></script>
<script type="text/javascript" src="../js/babel.min.js"></script>

<script type="text/babel">

  /*
需求: 定义一个todolist，开发思考流程
  1). 分析需求，划分组件：app父组件，add子组件，list子组件
  2). 先定义一个静态的，再修改为动态的

  问题：数据保存在哪个组件？
  答案：看数据被哪些组件使用（需要），好几个组件要用的就放在父组件，个别的放在子组件
  */

  //1. 定义APP父组件,只能有一个根标签
  class App extends React.Component{

      constructor(props){
          super(props);
          this.state={
              todos:["吃饭","敲代码","睡觉"]
          }
          this.add = this.add.bind(this)
      }

      add(todo){
        const {todos} = this.state;
        todos.unshift(todo);
        this.setState({todos});
      }

      render(){
          const { todos } = this.state
//          console.log(todos.length)
          return (
              <div>
                <h1>一个简单的React实现TODOList</h1>
                <Add count={todos.length} add={this.add}/>
                <Tolist todos={this.state.todos} />
              </div>
          )
      }
  }

  //2.add 子组件
  class Add extends React.Component{

      constructor(props){
        super(props)
        this.addTodo = this.addTodo.bind(this);
      }

      addTodo(){
        //读取输入框数据
        const text = this.input.value.trim();
        //检查数据
        if(!text){
            return
        }
        //保存
        this.props.add(text);
        //清除输入框
        this.input.value = ''
      }

      render(){
          return(
              <div>
                <input type="text" ref={input => this.input = input}/>
                <button onClick={this.addTodo}>add #{this.props.count +1}</button>
              </div>

          )
      }
  }

  Add.propTypes = {
      count: PropTypes.number.isRequired,
      add: PropTypes.func.isRequired
  }

  //3.list 子组件
  class Tolist extends React.Component{

      render(){
          return(
                <ul>
                    {
                       this.props.todos.map((todo, index) => <li key={index}>{todo}</li>)
                    }
                </ul>
          )
      }

  }

  Tolist.propTypes = {
      todos: PropTypes.array.isRequired
  }

  //只需要渲染父组件
  ReactDOM.render(<App />,
    document.getElementById('example'))
</script>
</body>
</html>

